<template>
	<div class="app-group-select" @click.stop="open">
		<div class="app-group-select__content">
			<span v-if="!multiple" class="app-group-select__content__text">
				{{ selectName }}
			</span>
			<template v-else>
				<div
					v-for="(select, index) of selects"
					:key="index"
					class="app-group-select__content__item"
				>
					<span class="item__label">{{ select.label }}</span>
					<CloseCircleOutlined
						class="item__close"
						v-if="!disabled"
						@click.stop="remove(select.id)"
					>
					</CloseCircleOutlined>
				</div>
			</template>
		</div>
		<div class="app-group-select__open">
			<CloseCircleOutlined
				v-if="!disabled && !multiple && selects.length > 0"
				class="app-group-select__open__close"
				@click.stop="remove(selects[0])"
			></CloseCircleOutlined>
			<SearchOutlined
				v-if="!noButton"
				class="app-group-select__open__search"
				@click.stop="openView"
			>
			</SearchOutlined>
		</div>
		<a-modal
			v-model:visible="openModal"
			:footer="null"
			centered
			destroyOnClose
			width="80%"
			:bodyStyle="{
				height: 'calc(100vh - 200px)',
				'justify-content': 'center',
			}"
		>
			<AppGroupSelect
				ref="groupSelectRef"
				:groupSelectParam="groupSelectParam"
				:groupSelectContext="groupSelectContext"
				@Change="groupSelect"
			></AppGroupSelect>
		</a-modal>
	</div>
</template>
<script setup lang="ts">
import { Ref } from 'vue';
import { personnelSelectProps } from './org-personnel-select';
import { CloseCircleOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { IEvent, IParam } from '@/core';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(personnelSelectProps);
const emit = defineEmits<EditorEmit>();
const selects: Ref<any> = ref([]);
const openModal = ref(false);
let groupSelectParam = ref({});
let groupSelectContext = ref({});
const groupSelectRef = ref();
//单选时选中名称
const selectName = computed(() => {
	if (selects.value.length > 0) {
		return selects.value[0].label;
	}
});
watch(
	() => props.data,
	(newVal: any, oldVal: any) => {
		selects.value = [];
		if (newVal) {
			let item: any = {};
			item.label =
				props.data && props.name && props.data[props.name]
					? props.data[props.name].split(',')
					: [];
			item.id =
				props.data && props.valueItem && props.data[props.valueItem]
					? props.data[props.valueItem].split(',')
					: [];
			if (props.fillMap) {
				for (let key in props.fillMap) {
					item[props.fillMap[key]] = props.data[key]
						? props.data[key].split(',')
						: [];
				}
			}
			const callback: any = (item: any) => {
				item.label.forEach((value: string, index: number) => {
					let _item: any = {};
					for (let key in item) {
						_item[key] = item[key][index] ? item[key][index] : null;
					}
					selects.value.push(_item);
				});
			};
			if (item.label.length == 0 && item.id.length > 0) {
				fillLabel(item, item.id, (result: any) => {
					item.label = result.label;
					callback(item);
				});
			} else {
				callback(item);
			}
		}
	},
	{
		immediate: true,
		deep: true,
	}
);

const open = (event: any) => {
	if (props.noButton) {
		openView(event);
	}
};
//删除数据
const remove = (select: any) => {
	selects.value.splice(
		selects.value.findIndex((item: any) => Object.is(select, item.id)),
		1
	);
	doEditorEmit();
};

//打开选择模态视图
const openView = (event: any) => {
	event.preventDefault();
	event.stopPropagation();
	const view: any = {
		codeName: 'AppGroupSelect',
		caption: App.ts('common.groupselect.groupselect', '分组选择'),
	};
	if (!view) {
		return;
	}
	const context: any = JSON.parse(JSON.stringify(props.context));
	let filtervalue = '';
	if (props.filter) {
		if (props.data[props.filter]) {
			filtervalue = props.data[props.filter];
		} else if (context[props.filter]) {
			filtervalue = context[props.filter];
		} else {
			filtervalue = context.srfsdept;
		}
	} else {
		filtervalue = context.srfsdept;
	}
	const param: any = {};
	Object.assign(param, {
		showtree: props.treeurl ? true : false,
		url: props.url,
		treeurl: props.treeurl,
		filtervalue: filtervalue,
		multiple: props.multiple,
		selects: selects.value,
		requestMode: props.requestMode,
	});
	if (props.context) {
		groupSelectContext.value = context;
		groupSelectParam.value = param;
		openModal.value = true;
	}
};

const groupSelect = (data: IParam[]) => {
	openModal.value = false;
	selects.value = [];
	if (data && data.length > 0) {
		selects.value = data;
	}
	doEditorEmit();
};

//抛值
const doEditorEmit = () => {
	let item: any = {};
	if (props.name) {
		item[props.name] = null;
	}
	if (props.valueItem) {
		item[props.valueItem] = null;
	}
	if (props.fillMap) {
		for (let key in props.fillMap) {
			item[key] = null;
		}
	}
	if (props.multiple) {
		selects.value.forEach((select: any) => {
			if (props.name) {
				item[props.name] = item[props.name]
					? `${item[props.name]},${select.label}`
					: select.label;
			}
			if (props.valueItem) {
				item[props.valueItem] = item[props.valueItem]
					? `${item[props.valueItem]},${select.id}`
					: select.id;
			}
			if (props.fillMap) {
				for (let key in props.fillMap) {
					item[key] = item[key]
						? `${item[key]},${select[props.fillMap[key]]}`
						: select[props.fillMap[key]];
				}
			}
		});
	} else {
		if (props.name) {
			item[props.name] =
				selects.value.length > 0 ? selects.value[0].label : null;
		}
		if (props.valueItem) {
			item[props.valueItem] =
				selects.value.length > 0 ? selects.value[0].id : null;
		}
		if (props.fillMap) {
			for (let key in props.fillMap) {
				item[key] =
					selects.value.length > 0
						? selects.value[0][props.fillMap[key]]
						: null;
			}
		}
	}
	for (let key in item) {
		emit('component-action', {
			name: key,
			action: 'valueChange',
			data: item[key],
		});
	}
};

const fillLabel = async (
	tempObject: any,
	valueItem: Array<any>,
	callback: any
) => {
	if (
		tempObject.label.length === 0 &&
		valueItem.length > 0 &&
		props.codelistTag &&
		props.codelistType &&
		Object.is(props.codelistType, 'DYNAMIC')
	) {
		await App.getAppCodeListHelper()
			.getCodeListItems(props.codelistTag)
			.then((codeListResult: any) => {
				if (codeListResult.ok) {
					const result = codeListResult.data;
					if (result && result.length > 0 && valueItem.length > 0) {
						let tempLabel: Array<any> = [];
						valueItem.forEach((value: any) => {
							let temp_result: any = result.find((item: any) => {
								return item.id === value;
							});
							tempLabel.push(temp_result.label);
						});
						Object.assign(tempObject, { label: tempLabel });
					}
					callback(tempObject);
				}
			})
			.catch((error: any) => {
				console.error(App.ts('common.generic.codenotexist'));
			});
	}
};
</script>
